import sys
sys.path.append("..")
import Cust.leancloudapi
GetApi = Cust.leancloudapi.GetApi()
studentm = GetApi.getStudent()
class Student:
    def getAllStudent(self):
      query = studentm.query
      query.limit(1000)
      query.include('ClassInfo')
      s = query.find()
      student_list = []
      for item in s:
           student_id = item.id
           student_name = item.get('StudentName')
           student_no = item.get('StudentNo')
           classm = item.get('ClassInfo')
           academy = classm.get('Academy')
           classname = classm.get('ClassName')
           classid = classm.id
           classinfo  = {'classid':classid,'academy':academy,'classname':classname}
           x = {'id':student_id,'name':student_name,'studentno':student_no,'classinfo':classinfo}
           student_list.append(x)
      return student_list
    def getStudent(self,id):
      query = studentm()
      res = query.create_without_data(id)
      res.fetch()
      studentname = res.get('StudentName')
      studentno = res.get('StudentNo')
      classid = res.get('ClassInfo')
      student = {'id':id,'studentname':studentname,'studentno':studentno,'classinfo':classid}
      return student
    def insertStu(self,name,studentno,classid):
      
      classinfo = GetApi.getClass()
      classm = classinfo.create_without_data(classid)
      student = studentm()
      student.set('StudentName',name)
      student.set('StudentNo',studentno)
      student.set('ClassInfo',classm)
      try:
          student.save()
          return 310
      except Exception as e:
          print e.message
          return 311
    def modifystudent(self,id,name,studentno,classid):
      classinfo = GetApi.getClass()
      classm = classinfo.create_without_data(classid)
      updatestudent = studentm.create_without_data(id)
      updatestudent.set('StudentName',name)
      updatestudent.set('StudentNo',studentno)
      updatestudent.set('ClassInfo',classm)
      try:
          updatestudent.save()
          return 330
      except Exception as e:
          print e.message
          return 321
    def delstudent(self,id):
      delstudent = studentm.create_without_data(id)
      try:
          delstudent.destroy()
          return 320
      except Exception as e:
          print e.message
          return 321
  
      